package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.yiboshi.rehrs.common.ZhongConfig;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.exception.ZyantExceptionUtils;
import com.yiboshi.rehrs.param.ZhongReq;
import com.yiboshi.rehrs.util.*;
import com.yiboshi.rehrs.util.js.AesUtils;
import com.yiboshi.rehrs.util.js.Qi5uxeel;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("HelperZhong_3")
@Slf4j
public class HelperJinshe extends HelperZhong {

    @Autowired
    ZhongConfigHelper configHelper;

    @Autowired
    IZhongUserService zhongUserService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisHelper redisHelper;

    @Autowired
    ProxyHelper proxyHelper;

    int mode = 3;

    public ZhongConfig getZhongConfig() {
        return configHelper.getConfig(3);
    }



    public Map<String, String> logonHeader(ZhongReq zhongReq) {
        ZhongUser zhongUser = new ZhongUser();
        zhongUser.setAccount(zhongReq.getAccount());
        zhongUser.setToken("");
        zhongUser.setPadId(zhongReq.getImei());
       /* ZhongUser one = zhongUserService.getOne(zhongReq.getAccount(), 0);
        if(one!=null){
            zhongUser.setPadId(one.getPadId());
        }else{
            zhongUser.setPadId("351564710852443");
        }*/
        log.info("logonHeaderNew zhongReq:{}",JSONObject.toJSONString(zhongReq));
        Map<String, String> stringMap = vipHeader(zhongUser, zhongReq);
        return stringMap;

    }

   /* public Map<String, String> logonHeaderOld(ZhongReq zhongReq) {
        Cache<String, Object> cache =
                CacheUtils.builder(3600);
        String account = zhongReq.getAccount();
        String imei = zhongReq.getImei();
        String time = zhongReq.getTime();
        if (StrUtil.isEmpty(time)) {
            time = (System.currentTimeMillis() / 1000) + "";
            zhongReq.setTime(time);
        }
        String type = zhongReq.getType();
        // 将对象转换为JSONObject
        JSONObject jsonObject = (JSONObject) JSON.toJSON(zhongReq);
        String key = "logonHeader_" + account;
        String token = (String) cache.getIfPresent(key);
        if (token == null) {
            //account=2153011500151&password=1234567&udid=23d0f01bdd89e3007aecb52067c0308f1&time=1742449826
            jsonObject.put("udid", "23d0f01bdd89e3007aecb52067c0308f1");
            jsonObject.put("password", "1234567");
            String format = data_init("account,password,udid,time", jsonObject);
            zhongReq.setOriginData(format);
            JSONObject init_logon_json = send(zhongReq, "logon");
            //init_logon_json {"token":"4d89a7d09f921ff9e74ffafcbe76c82e","tokenState":"y","info":{"uid":"15313","phone":null,"email":null,"acctno":"2153011500151","name":"\u6bb7\u5b8f\u73c5","pic":"","invID":"1","fen":"0","vipExpTime":"1742031567","vipExpDate":"2025-03-15 17:39:27","agent":"0"}}
            token = init_logon_json.getString("token");
            cache.put(key, token);
        }
        //token=4d89a7d09f921ff9e74ffafcbe76c82e&time=1742449827&path=https://211.156.197.65/pdalogin/p/common/loginbyusrface&pp=HONOR&xh=AQM-AL10&lx=0&qi5uxeel=
        jsonObject.put("token", token);
        long time_new = System.currentTimeMillis();
        jsonObject.put("time", time_new / 1000);
        jsonObject.put("path", getZhongConfig().getOtherMap().get("loginbyusrface"));
        String format = data_init("token,time,path", jsonObject);
        zhongReq.setOriginData(format);
        encode(zhongReq);
        JSONObject logon_json = send(zhongReq, "zyltlogin");
        String qi5uxeel = logon_json.getString("data");
        Map<String, String> map = new HashMap<>();
        map.put("qi5uxeel", qi5uxeel);
        map.put("pda_id", imei);
        map.put("person_no", account);
        map.put("Jdpt_req_time", time_new + "");
        map.put("Jdpt_sign", SHA256Util.Jdpt_sign(time_new + "", "", account));
        map.put("pda_user_token","");
        //合并其他header
        //map = meger(map);
        return map;

    }*/

    public Map<String, String> vipHeader(ZhongUser zhongSessionUser, ZhongReq zhongReq) {
        String type = zhongReq.getType();
        ZhongConfig zhongConfig = getZhongConfig();
        String path = zhongConfig.getOtherMap().get(type);
        Map<String, String> cpsMap = cpsMap2(path);
        if(CollUtil.isEmpty(cpsMap)){
            return null;
        }
        //ZyantExceptionUtils.e(CollUtil.isEmpty(cpsMap),"授权错误，请稍后再试");
        //redisHelper.increase(getMode(),use_type);
        //
        //
        //System.out.println(nn);
        //Map<String, String> map = configHelper.fiddleMap();
        //map.putAll(cpsMap);
        Map<String, String> stringMap = userHeaderMap(zhongSessionUser, type);
        cpsMap.putAll(stringMap);
        //合并其他header
        //String type_base = zhongReq.getType();
        return cpsMap;
    }

    @Override
    public Map<String, String> channelHeader( String uri,ZhongUser zhongUser) {
        //Cache<String, Object> builder = CacheUtils.builder(10);

        Map<String, String> stringStringMap = this.cpsMap2(uri);
        if(CollUtil.isEmpty(stringStringMap)){
            return null;
        }
        Map<String, String> stringMap1 = HelperJinshe.userHeaderMap(zhongUser,uri);
        stringStringMap.putAll(stringMap1);
        return stringStringMap;
    }


    public static Map<String, String> userHeaderMap(ZhongUser zhongUser,String type) {
        Map<String, String> stringMap = new HashMap<>();
        String pda_user_token = zhongUser.getToken();
        String person_no = zhongUser.getAccount();
        String time = (System.currentTimeMillis()+1000) + "";
        String padId = zhongUser.getPadId();
        if(StrUtil.isEmpty(padId)){
            padId = zhongUser.getImei();
        }
        if(StrUtil.isNotEmpty(padId)){
            stringMap.put("pda_id", padId);
        }else{
            stringMap.put("android_id", zhongUser.getAndroidId());
            stringMap.put("pda_id", "");
        }
        //android_id: c08d8c3ff856477d
        //stringMap.put("android_id", padId);

        stringMap.put("person_no", person_no);
        stringMap.put("pda_user_token", StrUtils.isBlank(pda_user_token)?"":pda_user_token);
        String jdpt_sign = SHA256Util.Jdpt_sign(time, pda_user_token, person_no);
        stringMap.put("jdpt_sign",jdpt_sign );
        stringMap.put("jdpt_req_time", time);
        //stringMap.put("Jdpt_sign", jdpt_sign);
        //stringMap.put("Jdpt_req_time", time);
        stringMap.put("pda_version","248");
        stringMap.put("pda_network","3");
        stringMap.put("version_name","1.4.9");
        if(type!=null&&type.contains("newCallAndFile")){
            stringMap.put("user-agent","okhttp/3.10.0");
            stringMap.put("content-type","application/x-www-form-urlencoded; charset=utf-8");
        }
        return stringMap;
    }


    // String encrypt = AesUtils.encrypt("-cpsVer=1cpsTime=" + System.currentTimeMillis() + "cpsOs=ANDROID-Linux-3.18.108-g6895615cpsCtx=0", "B+oQ52IuAt9wbMxw");
    // RequestCall build = url.addHeader("Cps-Magic", String.valueOf(StringsKt.replace$default(encrypt, "\n", "", false, 4, (Object) null))).mediaType(parse).content(GsonUtils.INSTANCE.toJson(arrayMap3)).build();
    //http://211.156.197.65

    //1.01080-ni版本piliang.php
    public Map<String, String> cpsMap2(String path) {
       // return cpsMap(path);
        //ZhongConfig zhongConfig = getZhongConfig();
        //String path = zhongConfig.getOtherMap().get(type);
        /*Cache<String, Object> builder = CacheUtils.builder(10);
        Object ifPresent = builder.getIfPresent(path);
        if(ifPresent!=null){
            return (Map)ifPresent;
        }*/
        String key = "cps-value:js:"+path;
        int time =getTimeOut(path);
        String mapStr = time<=0?"":stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(mapStr)){
            log.info("jinshe redis cache cps,path:{}",path);
            return JacksonUtils.toMap(mapStr,String.class,String.class);
        }

        String n1Key = "jsqi5:n1";
        String n1 = CacheUtils.getByCache10Min(n1Key, String.class);
        if(StrUtils.isBlank(n1)){
            n1 = Qi5uxeel.buildN1();
            CacheUtils.putByCache10Min(n1Key, n1);
        }
        String timeAes = getZhongConfig().getUriMap().get("timeAes");
        String apiPhp = getZhongConfig().getUriMap().get("apiPhp");
        if(RehrsSystemConfig.isDev()){
            apiPhp = "http://qi5.mmlwo.cn/get1/piliang.php";
        }
        String postPiliangRes = "";

        try{
            //n1 = StrUtils.isBlank(n1)?"4fWTFeimEYjnvBVwXI3yIqq":n1;
            //n1 = "rKz_Fj0OUkudUQUy6hAKiaq";
            //String timeAes = Qi5uxeel.buildTimeAes();
            //timeAes = "2025050214011625";

            String encrypt = AesUtils.encrypt(path,timeAes).replaceAll("\n","");
            encrypt = URLEncoder.encode(encrypt,"utf-8");
            String data = encrypt;
            String encrypt2 = AesUtils.encrypt(n1, timeAes).replaceAll("\n","");
            String sign = URLEncoder.encode(encrypt2,"utf-8");;
            long currentTimeMillis = System.currentTimeMillis() / 1000;
            String ua = JinsheUtil.buildUA(currentTimeMillis);
            String requestStr = String.format("data=%s&sign=%s", data, sign);
            //requestStr = "data=j65E%2B6i%2BwAdkHLvxnVbDAU5b2KIoITtCaEiGdxVJf1vFildonhs79dcveMFtDbTr&sign=kjrOex4Kl%2BXE01Nh3qifwDFWhtqsrcewGOsAG9gSaxk%3D";
            log.info("mode 3 get cps path:{}  timeAes:{} ,requestStr:{}",path,timeAes,requestStr);
            long timeStart = System.currentTimeMillis();
            OkHttpUtil post = new OkHttpUtil().url(apiPhp)
                    .timeoutMillis(500)
                    .retryCount(3)
                    .addHeader("User-Agent", ua)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    //.proxySupplier(() -> proxyHelper.one())
                    .post(requestStr.getBytes());
            if(!RehrsSystemConfig.isDev()){
                post.proxySupplier(() -> proxyHelper.one());
            }
            postPiliangRes = post.execute();

            if(StrUtils.isNotBlank(postPiliangRes)&&postPiliangRes.contains("<html>")){
                log.info("jinshe 授权拦截 res:{}",postPiliangRes.length()>30?postPiliangRes.substring(0,30):postPiliangRes);
                postPiliangRes =new OkHttpUtil().url(apiPhp)
                        .timeoutMillis(500)
                        .retryCount(0) //不重试
                        .addHeader("User-Agent", ua)
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        //.proxySupplier(() -> proxyHelper.one())
                        .post(requestStr.getBytes()).execute();
            }
            long timeEnd = System.currentTimeMillis();
            log.info("jinshe cps header 耗时:{} ms",(timeEnd-timeStart));
            if(StrUtils.isNotBlank(postPiliangRes)&&postPiliangRes.contains("<html>")){
                ZyantExceptionUtils.x(true,"授权异常");
            }
            //og.info("postPiliang:{}",postPiliangRes);
            String postPiliang = AesUtils.decrypt(postPiliangRes,timeAes);
            JSONObject jsonObject = JSONObject.parseObject(postPiliang);
            Map<String, String> stringStringMap = new HashMap<>();
            String data1 = jsonObject.getString("data");
            ZyantExceptionUtils.x(StrUtils.isBlank(data1),"授权异常");
            stringStringMap.put("qi5uxeel",data1 );
            stringStringMap.put("cps-magic", jsonObject.getString("cps"));
            if(time>0){
                stringRedisTemplate.opsForValue().set(key,JacksonUtils.toString(stringStringMap),time, TimeUnit.SECONDS);
            }
            //builder.put(path,stringStringMap);
            return stringStringMap;
        }catch (Exception e){
            log.error("授权异常,postPiliangRes:{}",postPiliangRes,e);
            return null;
        }

    }



    //1.01076-n1版本api.php


    public int getMode() {

        return mode;
    }

    @Override
    protected void deleteVipTokenCache() {
        throw  new RuntimeException("未实现的方法");
    }

    @Override
    protected JSONObject decode(String dataStr) {
        return null;
    }


}
